package jee.boot.module.crud.service;

import jee.boot.common.basic.CrudService;
import jee.boot.common.basic.ServiceException;
import jee.boot.common.utils.JsonMapper;
import jee.boot.module.crud.dao.DemoCrudDao;
import jee.boot.module.crud.entity.DemoCrud;
import jee.boot.entity.file.Attachment;
import jee.boot.entity.task.IexpTask;
import jee.boot.module.iexp.excel.template.ExportTemplateExcelExecutor;
import jee.boot.module.iexp.service.IexpTaskService;
import jee.boot.entity.log.LeaveTraces;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 示例-单表操作Service
 * @author
 * @version 2019-06-19
 */
@Service
public class DemoCrudService extends CrudService<DemoCrudDao, DemoCrud> {

    @Autowired
    private IexpTaskService iexpTaskService;
    @Override
    @LeaveTraces(operator= LeaveTraces.Type.SAVE)
    public void save(DemoCrud entity) {
        super.save(entity);
    }
    @LeaveTraces(operator= LeaveTraces.Type.UPDATE)
    public void update(DemoCrud entity) {
        super.update(entity);
    }
    @LeaveTraces(operator= LeaveTraces.Type.DELETE)
    public void delete(DemoCrud entity) {
        super.delete(entity);
    }


    @Override
    public Object importData(MultipartFile file) {
        Attachment attachment = super.storeFile(file);
        Map<String, Object> param = new HashMap<>();
        param.put("headerNum", 2);
        param.put("sheetIndexOrName", 0);
        IexpTask task = IexpTask.createNewImpTask("demoImport", JsonMapper.toJsonString(param), attachment.getFileName());
        task.setAttachment(attachment);
        task.setName("Demo导入");
        iexpTaskService.save(task);
        return null;
    }

    @Override
    public void exportData(DemoCrud entity, HttpServletResponse response) {
        IexpTask task = IexpTask.createNewExpTask("demoExport", JsonMapper.toJsonString(entity));
        task.setName("Demo导出");
        // 存储后台任务
        iexpTaskService.save(task);
    }

    @Override
    public void importTemplate(DemoCrud entity, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        map.put("list", new ArrayList<>());
        try {
            new ExportTemplateExcelExecutor()
                    .initByTemplateNameAndData("DemoExport.xlsx", map)
                    .buildExcel()
                    .write(response, "demo模板导出").dispose();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw new ServiceException();
        }
    }



}